#include "monitor.h"
#include "ui_monitor.h"
#include <QFileDialog>


Monitor::Monitor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Monitor)
{
    ui->setupUi(this);
    saveimg = false;
    ui->m_label->setGeometry(80,50,500,400);
    ui->m_label->setScaledContents(true);
    ui->m_label->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    hlayout.addWidget(ui->m_label);
    this->setLayout(&hlayout);
}

Monitor::~Monitor()
{
    delete ui;
}

void Monitor::onReadyread()
{
    char spos[3] = {(char)0xff,(char)0xd8};
    char epos[3] = {(char)0xff,(char)0xd9};
    streambuf.append(reply->readAll());
    int startpos = streambuf.indexOf(spos,0);
    if(startpos == -1){
        streambuf.clear();
        return;
    }
    int endpos = streambuf.indexOf(epos,startpos);
    if(endpos == -1)
    {
        return;
    }
    QByteArray imagebuffer = streambuf.mid(startpos,endpos-startpos+2);
    QImage img;
    bool res = img.loadFromData(imagebuffer,"JPG");
    if(res == false){
        qDebug() <<"失败";
        streambuf.clear();
        return;
    }
    else
    {
        img = img.mirrored(true,false);
        if(saveimg)
        {
            static int num = 1;
            QString filepath = "D:/qt/gateway_app/picture/" +QString::number(num)+".JPG";
            bool saved = img.save(filepath,"JPG");
            if(saved)
            {
                qDebug()<<"Image save successfly";
            }
            else
            {
                qDebug()<<"Falsed to save image";
            }
            saveimg = false;
            num++;
        }
        ui->m_label->setPixmap(QPixmap::fromImage(img));
        streambuf.clear();

    }
}

void Monitor::slotReadError(QNetworkReply::NetworkError)
{
    reply = manager.get(QNetworkRequest(QUrl("http://192.168.1.60:8080/?action=stream")));
    connect(reply,&QNetworkReply::readyRead,this,&Monitor::onReadyread);
    connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),
            this,SLOT(slotReadError(QNetworkReply::NetworkError)));
}

void Monitor::on_m_start_clicked()
{
    reply = manager.get(QNetworkRequest(QUrl("http://192.168.179.37:8080/?action=stream")));
    connect(reply,&QNetworkReply::readyRead,this,&Monitor::onReadyread);
    connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),
            this,SLOT(slotReadError(QNetworkReply::NetworkError)));
}


void Monitor::on_m_stop_clicked()
{
//    reply = nullptr;
    reply = manager.get(QNetworkRequest(QUrl(" ")));
    streambuf.clear();
    ui->m_label->clear();
    ui->m_label->setStyleSheet("background-color: rgb(0, 0, 0);");
}

void Monitor::on_m_photo_clicked()
{
    saveimg = true;
}

void Monitor::on_pushButton_4_clicked()
{
    QString filepath = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                   "D:/qt/gateway_app/picture/",
                                                   tr("Images (*.JPG)"));
    if(filepath.isEmpty())
    {
        return;
    }
}
